<template>
  <div class="reception-consult">
    <el-card class="consult-container">
      <template #header>
        <div class="card-header">
          <span>前台咨询管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddConsult">
              <el-icon><Plus /></el-icon>
              添加咨询记录
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="consult-content">
        <!-- 搜索和过滤区域 -->
        <div class="search-filter">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input
                v-model="searchForm.keyword"
                placeholder="搜索咨询内容或咨询人"
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.status" placeholder="状态筛选" clearable @change="handleSearch">
                <el-option label="全部" value="" />
                <el-option label="未处理" value="未处理" />
                <el-option label="已处理" value="已处理" />
                <el-option label="已回复" value="已回复" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleSearch"
              />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </div>
        
        <!-- 咨询列表 -->
        <div class="consult-list">
          <el-table 
            :data="filteredConsultList" 
            style="width: 100%" 
            empty-text="暂无咨询记录"
            v-loading="loading"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="咨询人" width="120" />
            <el-table-column prop="phone" label="联系电话" width="150" />
            <el-table-column prop="content" label="咨询内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="replyContent" label="回复内容" min-width="200" show-overflow-tooltip>
              <template #default="scope">
                <span :class="{ 'no-reply': !scope.row.replyContent }">
                  {{ scope.row.replyContent || '暂无回复' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag 
                  :type="getStatusType(scope.row.status)"
                  effect="light"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="咨询时间" width="180" />
            <el-table-column prop="replyTime" label="回复时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewDetail(scope.row)">
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
                <el-button 
                  type="success" 
                  link 
                  @click="handleReply(scope.row)"
                  :disabled="scope.row.status === '已处理'"
                >
                  <el-icon><ChatDotRound /></el-icon>
                  回复
                </el-button>
                <el-button 
                  type="warning" 
                  link 
                  @click="handleProcess(scope.row)"
                  :disabled="scope.row.status === '已处理'"
                >
                  <el-icon><Check /></el-icon>
                  处理
                </el-button>
                <el-button 
                  type="danger" 
                  link 
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 咨询详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="咨询详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <div class="consult-detail" v-if="currentConsult">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="咨询人">{{ currentConsult.name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentConsult.phone }}</el-descriptions-item>
          <el-descriptions-item label="咨询时间" :span="2">{{ currentConsult.createTime }}</el-descriptions-item>
          <el-descriptions-item label="咨询内容" :span="2">
            <div class="content-text">{{ currentConsult.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="回复内容" :span="2">
            <div class="content-text">{{ currentConsult.replyContent || '暂无回复' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="回复时间">{{ currentConsult.replyTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusType(currentConsult.status)">
              {{ currentConsult.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="handleReply(currentConsult)"
            :disabled="currentConsult && currentConsult.status === '已处理'"
          >
            回复咨询
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加咨询对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加咨询记录"
      width="500px"
      :before-close="handleAddClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="咨询人" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入咨询人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="咨询内容" prop="content">
          <el-input
            v-model="addForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入咨询内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddClose">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, View, ChatDotRound, Check, Delete } from '@element-plus/icons-vue'

// 响应式数据
const consultList = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const addDialogVisible = ref(false)
const addLoading = ref(false)
const currentConsult = ref(null)
const addFormRef = ref()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
})

// 添加表单
const addForm = reactive({
  name: '',
  phone: '',
  content: ''
})

// 表单验证规则
const addFormRules = {
  name: [
    { required: true, message: '请输入咨询人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入咨询内容', trigger: 'blur' },
    { min: 10, message: '咨询内容至少10个字符', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 模拟咨询数据
const mockConsultData = [
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    content: '想了解养老院的服务内容和收费标准，包括房间类型、餐饮服务、医疗护理等具体信息。',
    replyContent: '您好！我们提供单人间、双人间、三人间等多种房型，收费标准根据房型和服务等级有所不同。具体可来电咨询或预约参观。',
    status: '已回复',
    createTime: '2025-10-04 10:30:00',
    replyTime: '2025-10-04 11:00:00'
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139000',
    content: '咨询老人入住条件和流程，需要准备哪些材料？',
    replyContent: '',
    status: '已处理',
    createTime: '2025-10-03 15:20:00',
    replyTime: '2025-10-03 16:00:00'
  },
  {
    id: 3,
    name: '王五',
    phone: '13700137000',
    content: '养老院有哪些娱乐活动和康复训练项目？',
    replyContent: '我们提供书法、绘画、棋牌、健身操等多种娱乐活动，还有专业的康复训练和理疗服务。',
    status: '已回复',
    createTime: '2025-10-03 09:15:00',
    replyTime: '2025-10-03 10:00:00'
  },
  {
    id: 4,
    name: '赵六',
    phone: '13600136000',
    content: '可以安排试住体验吗？试住期间如何收费？',
    replyContent: '',
    status: '未处理',
    createTime: '2025-10-02 14:45:00',
    replyTime: null
  },
  {
    id: 5,
    name: '钱七',
    phone: '13500135000',
    content: '请问养老院的医疗护理服务包含哪些内容？是否有专业医生值班？',
    replyContent: '我们提供24小时医疗护理服务，包括日常健康监测、用药管理、紧急医疗救助等，并有专业医生定期巡诊。',
    status: '已回复',
    createTime: '2025-10-02 11:20:00',
    replyTime: '2025-10-02 12:00:00'
  },
  {
    id: 6,
    name: '孙八',
    phone: '13400134000',
    content: '家属探访时间和规定是怎样的？',
    replyContent: '家属探访时间为每周六、日下午2-5点，需提前预约。疫情期间请配合做好防疫措施。',
    status: '已回复',
    createTime: '2025-10-01 16:30:00',
    replyTime: '2025-10-01 17:00:00'
  },
  {
    id: 7,
    name: '周九',
    phone: '13300133000',
    content: '老人有特殊饮食需求（如糖尿病、高血压）如何安排？',
    replyContent: '',
    status: '未处理',
    createTime: '2025-10-01 13:10:00',
    replyTime: null
  },
  {
    id: 8,
    name: '吴十',
    phone: '13200132000',
    content: '养老院的安全保障措施有哪些？',
    replyContent: '我们配备24小时监控系统、紧急呼叫系统、消防设施等，确保老人安全。',
    status: '已回复',
    createTime: '2025-09-30 10:05:00',
    replyTime: '2025-09-30 10:30:00'
  },
  {
    id: 9,
    name: '郑十一',
    phone: '13100131000',
    content: '费用包含哪些项目？是否有额外收费？',
    replyContent: '费用包含住宿、餐饮、基础护理等，特殊医疗服务和个性化服务可能产生额外费用。',
    status: '已回复',
    createTime: '2025-09-29 15:40:00',
    replyTime: '2025-09-29 16:15:00'
  },
  {
    id: 10,
    name: '冯十二',
    phone: '13000130000',
    content: '老人外出就医如何安排？',
    replyContent: '',
    status: '未处理',
    createTime: '2025-09-28 09:25:00',
    replyTime: null
  }
]

// 加载咨询数据
const loadConsultData = async () => {
  loading.value = true
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 使用模拟数据
    consultList.value = [...mockConsultData]
    pagination.total = consultList.value.length
    
    ElMessage.success(`成功加载 ${consultList.value.length} 条咨询记录`)
  } catch (error) {
    ElMessage.error('加载咨询数据失败')
    console.error('加载咨询数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 过滤后的咨询列表
const filteredConsultList = computed(() => {
  let filtered = consultList.value

  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(keyword) ||
      item.phone.includes(keyword) ||
      item.content.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }

  // 日期范围筛选
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    filtered = filtered.filter(item => {
      const createDate = new Date(item.createTime)
      return createDate >= new Date(startDate) && createDate <= new Date(endDate)
    })
  }

  // 更新分页总数
  pagination.total = filtered.length

  // 分页处理
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  const endIndex = startIndex + pagination.pageSize
  return filtered.slice(startIndex, endIndex)
})

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '未处理': 'danger',
    '已处理': 'warning',
    '已回复': 'success'
  }
  return statusMap[status] || 'info'
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  ElMessage.success('搜索完成')
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.dateRange = []
  pagination.currentPage = 1
  ElMessage.success('搜索条件已重置')
}

// 查看详情
const handleViewDetail = (consult) => {
  currentConsult.value = { ...consult }
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentConsult.value = null
}

// 回复咨询
const handleReply = async (consult) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入回复内容', '回复咨询', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入回复内容...',
      inputType: 'textarea',
      inputValidator: (value) => {
        if (!value) {
          return '回复内容不能为空'
        }
        if (value.length < 5) {
          return '回复内容至少5个字符'
        }
        return true
      }
    })

    if (value) {
      // 更新咨询状态
      const index = consultList.value.findIndex(item => item.id === consult.id)
      if (index !== -1) {
        consultList.value[index].replyContent = value
        consultList.value[index].status = '已回复'
        consultList.value[index].replyTime = new Date().toLocaleString('zh-CN')
        
        ElMessage.success('回复成功')
        
        // 如果正在查看详情，更新详情数据
        if (currentConsult.value && currentConsult.value.id === consult.id) {
          currentConsult.value = { ...consultList.value[index] }
        }
      }
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 处理咨询
const handleProcess = async (consult) => {
  try {
    await ElMessageBox.confirm(
      '确定要将此咨询标记为已处理吗？',
      '处理咨询',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 更新咨询状态
    const index = consultList.value.findIndex(item => item.id === consult.id)
    if (index !== -1) {
      consultList.value[index].status = '已处理'
      consultList.value[index].replyTime = new Date().toLocaleString('zh-CN')
      
      ElMessage.success('咨询已标记为已处理')
      
      // 如果正在查看详情，更新详情数据
      if (currentConsult.value && currentConsult.value.id === consult.id) {
        currentConsult.value = { ...consultList.value[index] }
      }
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 删除咨询
const handleDelete = async (consult) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条咨询记录吗？此操作不可恢复。',
      '删除咨询',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const index = consultList.value.findIndex(item => item.id === consult.id)
    if (index !== -1) {
      consultList.value.splice(index, 1)
      ElMessage.success('咨询记录删除成功')
      
      // 重新加载数据以更新分页
      loadConsultData()
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 添加咨询记录
const handleAddConsult = () => {
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = ''
  })
  addDialogVisible.value = true
}

// 关闭添加对话框
const handleAddClose = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
}

// 提交添加表单
const handleAddSubmit = async () => {
  if (!addFormRef.value) return

  try {
    // 验证表单
    await addFormRef.value.validate()
    
    addLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建新的咨询记录
    const newConsult = {
      id: Math.max(...consultList.value.map(item => item.id)) + 1,
      name: addForm.name,
      phone: addForm.phone,
      content: addForm.content,
      replyContent: '',
      status: '未处理',
      createTime: new Date().toLocaleString('zh-CN'),
      replyTime: null
    }
    
    // 添加到列表
    consultList.value.unshift(newConsult)
    
    ElMessage.success('咨询记录添加成功')
    addDialogVisible.value = false
    addFormRef.value.resetFields()
    
    // 重置分页到第一页
    pagination.currentPage = 1
    
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请检查表单填写是否正确')
    } else {
      ElMessage.error('添加咨询记录失败')
    }
  } finally {
    addLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.currentPage = 1
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
}

// 刷新数据
const refreshData = () => {
  loadConsultData()
}

onMounted(() => {
  loadConsultData()
})
</script>

<style scoped>
.reception-consult {
  padding: 20px;
}

.consult-container {
  min-height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.consult-content {
  margin-top: 20px;
}

.consult-list {
  margin-top: 20px;
}

.consult-actions {
  text-align: right;
}
</style>
